package MasterManagers.SocketManager;

import MasterManagers.TableManager;
import MasterManagers.utils.SocketUtils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketManager {
    private TableManager tableManager;
    private ServerSocket serverSocket;
    public SocketManager(int PORT, TableManager tableManager) throws IOException, InterruptedException {
        this.tableManager = tableManager;
        this.serverSocket = new ServerSocket(PORT);
    }
    /**
     * 1. 主节点启动
     * 2. 从节点启动，完成zookeeper的注册
     * 3. 客户端建表指令<C2M>[2]tableName，负载均衡处理后返回给客户端<M2C>[2]tableName,ip:port,ip:port,ip:port，
     *    同时向对应的三个region分别发送建表指令<M2R>[4]tableName
     * 4. 客户端查找region指令<C2M>[1]tableName，本地找表对应的三个region并返回
     * 5. 客户端请求所有表名<C2M>[3]，本地找所有表名并返回
     * 6. 容错容灾：检测到region失效后，负载均衡选择一个region，向其发送<M2R>[5]tableName,ip:port，让它向对应ip的region请求tableName表的信息,
     *    同时master向所有client通知更新region   <M2C>[7]tableName,旧的ip:port,新的ip:port
     * 7. 恢复后上线，主节点向其发送<M2R>[8]，通知其删除所有表和日志
     */
    public void startWorking() throws InterruptedException, IOException {
        while(true){
            Thread.sleep(200);
            Socket socket = serverSocket.accept();
            SocketThread socketThread = new SocketThread(socket, tableManager);
            String ip = socket.getInetAddress().getHostAddress();
            System.out.println(ip);
            if(ip.equals("127.0.0.1"))
                ip = SocketUtils.getHostAddress();
//            tableManager.addClient(ip);
            tableManager.addSocketThread(ip, socketThread);
            Thread thread = new Thread(socketThread);
            thread.start();
        }
    }
}
